package com.complex.spring.advance.service.messagesource;

import java.util.ArrayList;
import java.util.List;

/**
 * 事件发布者类
 * @author gao
 *
 */
public class MethodExecutionEventPublisher {
	//这个listener容器,其实与spring中的ApplicationEventPublisher十分相似 
	private List<MethodExecutionEventListener> listeners = new ArrayList<MethodExecutionEventListener>();
	
	public void methodToMonitor(){
		MethodExecutionEvent event2Publish = new MethodExecutionEvent(this,"methodToMonitor");
		//发布开始事件
		publishEvent(MethodExecutionStatus.BEGIN,event2Publish);
		//TODO 处理自己的业务
		
		//发布结束事件
		publishEvent(MethodExecutionStatus.END,event2Publish);
	}
	
	protected void publishEvent(MethodExecutionStatus status,MethodExecutionEvent methodExecutionEvent){
		List<MethodExecutionEventListener> copyListeners = new ArrayList<MethodExecutionEventListener>(listeners);
		
		for(MethodExecutionEventListener listener:copyListeners){
			if(MethodExecutionStatus.BEGIN.equals(status)){
				listener.onMethodBegin(methodExecutionEvent);
			}else{
				listener.onMethodEnd(methodExecutionEvent);
			}
		}
	}
	
	public void addMethodExecutionEventListener(MethodExecutionEventListener listener){
		this.listeners.add(listener);
	}
	public void removeListener(MethodExecutionEventListener listener){
		if(this.listeners.contains(listener)){
			this.listeners.remove(listener);
		}
	}
	public void removeAllListeners(){
		this.listeners.clear();
	}
	
	
	public static void main(String[] args) {
		MethodExecutionEventPublisher eventPublisher = new MethodExecutionEventPublisher();
		eventPublisher.addMethodExecutionEventListener(new SimpleMethodExecutionEventListener());
		eventPublisher.methodToMonitor();
	}
}
